package com.dudu.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

import core.util.IoUtils;

/**
 * 异常处理工具类
 * @author zx
 *
 */
public final class ExceptionUtils {
	
	private ExceptionUtils(){
		
	}
	
	/**
	 * 获取根级异常
	 * @param exp
	 * @return
	 */
	public static Throwable getRootException(Throwable exp) {
		if (exp == null)
			return null;
		Throwable cause = exp;
		Throwable err = exp.getCause();
		while (err != null) {
			cause = err;
			err = cause.getCause();
		}
		return cause;  
	}
	
	/**
	 * 返回根异常的堆栈信息
	 * limit未设置时默认长度为128
	 * @param exp
	 * @return
	 */
	public static String getStackTraceCauseMessage(Throwable exp,int limit){
		if(limit<=0)
			limit=128;
		exp=getRootException(exp);
		if(exp==null)
			return "";
		StringWriter writer=null;
		PrintWriter pw=null;
		String msg="";
		try{
			writer=new StringWriter(64);
			pw=new PrintWriter(writer);
			exp.printStackTrace(pw);
			msg=writer.toString();
		}catch(Exception err){
			
		}finally{
			IoUtils.close(writer);
			IoUtils.close(pw);  
		}
		if(msg!=null&&msg.length()>limit){
			msg=msg.substring(0, limit);
		}
		return msg;
	}

}
